import { Text, View } from '@tarojs/components'
import { useMemo, useState } from 'react'
import { useMount } from '@/hooks'
import Taro from '@tarojs/taro'
import to from 'await-to-js';
import { Card, CdnImage, CheckboxInput, Form, ImagePicker, PrimaryButton, TextArea, TextItem } from '@/ui-components'
import { TaskOwnerName, TaskTypeImage } from '@/constants'
import dayjs from 'dayjs'
import { useAppSelector } from '@/store/hooks';
import { TreasuryRole } from '@/types';
import { dialog } from '@/utils';
import { SubmitTaskParams, TreasuryTaskDetail, getTreasuryTaskDetail, submitTask } from '../../network'
import './index.scss'


interface treasuryTaskState extends SubmitTaskParams {
  isComplete: boolean
}

export default function TreasuryTaskDetailPage() {
  const [treasuryTask, setTreasuryTask ] = useState<TreasuryTaskDetail | undefined >(undefined)
  const [submitParams, setSubmitParams] = useState<treasuryTaskState>({} as treasuryTaskState)

  const userTreasury = useAppSelector(state => state.treasury.userTreasury)
  const treasuryTaskId = useMemo(() => {
    return Number(Taro.getCurrentInstance().router?.params.treasuryTaskId)
  }, [])

  useMount(async () => {
    const [err, treasuryTask] = await to(getTreasuryTaskDetail(treasuryTaskId))
    if (err) return
    setTreasuryTask(treasuryTask)
  })

  const submitTreasuryTask = async () => {
    submitParams.treasuryTaskId = treasuryTaskId
    const [err] = await to(submitTask(submitParams))
    if (err) {
      Taro.showToast({ title: '提交任务失败', icon: 'none' })
    } else {
      Taro.showToast({ title: '提交任务成功', icon: 'success' })
      Taro.navigateBack()
    }
  }

  const showSubmitDialog = () => {
    Dialogconfirm({
      content: '是否确认提交任务？',
      onConfirm: submitTreasuryTask
    })
  }

  if (!treasuryTask) {
    return <View />
  }

  return (
    <View className='treasury-task-detail safe-bottom'>
      <Card>
        <View className='p-normal row-start-stretch'>
          <CdnImage src={TaskTypeImage[treasuryTask.type]} className='image-160 border-radius-small' />
          <View className='column-between-start flex-1 mh-medium'>
            <View className='text-title'>{treasuryTask.name}</View>
            <View className='text-normal'>{treasuryTask.description}</View>
          </View>
        </View>
        <Form>
          <View className='p-normal row-start-center'>
            <View className='flex-1'>
              <View className='text-large-fail text-center'>
                { dayjs(treasuryTask.deadline).diff(dayjs(), 'day') }
              </View>
              <View className='text-primary-bold mt-medium text-center'>
                剩余天数
              </View>
            </View>
            <View className='flex-1'>
              <View className='text-large-fail text-center'>
                { treasuryTask.submitCount }
              </View>
              <View className='text-primary-bold mt-medium text-center'>
                已提交数
              </View>
            </View>
            <View className='flex-1'>
              <View className='text-large-fail text-center'>
                { treasuryTask.score }
              </View>
              <View className='text-primary-bold mt-medium text-center'>
                价值积分
              </View>
            </View>
          </View>
          <TextItem
            label='发布人'
            value={TaskOwnerName[treasuryTask.owner]}
          />
          <TextItem
            label='指定情况'
            value={treasuryTask.assignee}
          />
          <TextItem
            label='奖励积分'
            renderRight={() => (
              <View className='text-primary'>
                <Text className='success'>{treasuryTask.score}</Text>（已扣除手续费<Text className='success'>0</Text>）
              </View>
            )}
          />
        </Form>
      </Card>
      {
        [TreasuryRole.admin, TreasuryRole.owner].includes(userTreasury.treasuryRole) ? <Card>
          <View className='pv-normal row-aroud-center task-operation'>
            <View className='column-start-center'>
              <CdnImage src='/common/task/task-copy.png' className='image-48' />
              <View className='text-center text-primary mt-normal'>复制任务</View>
            </View>
            <View className='line' />
            <View className='column-start-center'>
              <CdnImage src='/common/task/task-delete.png' className='image-48' />
              <View className='text-center text-primary mt-normal'>任务作废</View>
            </View>
            <View className='line' />
            <View className='column-start-center'>
              <CdnImage src='/common/task/task-close.png' className='image-48' />
              <View className='text-center text-primary mt-normal'>任务关闭</View>
            </View>
          </View>
        </Card> : null
      }
      <Card>
        <CheckboxInput
          label='任务完成'
          value={submitParams.isComplete}
          options={[
            { name: '是', value: true },
            { name: '否', value: false }
          ]}
          onChange={isComplete => setSubmitParams({ ...submitParams, isComplete })}
        />
        <TextArea
          label='补充说明'
          placeholder='请输入补充说明'
          value={submitParams.note}
          onChange={note => setSubmitParams({ ...submitParams, note })}
        />
        <ImagePicker
          images={submitParams.image ? [submitParams.image] : []}
          onChange={(images) => setSubmitParams({ ...submitParams, image: images[0] })}
          title='补充图片'
          count={1}
        />
      </Card>
      <PrimaryButton
        text='提交任务'
        onClick={showSubmitDialog}
        disabled={!submitParams.isComplete}
      />
    </View>
  )
}
